//
//  EmojiView.swift
//  1-自定义键盘搭建
//
//  Created by yellow on 15/10/23.
//  Copyright © 2015年 yellow. All rights reserved.
//

import UIKit
import SnapKit

//cell重用标示符
let EmojiViewCellId = "EmojiViewCellId"

class EmojiView: UIView {
    
    /// emoji表情包数组
    private lazy var emojiPackages = EmojiManager.shareManager.emojiPackages
    
    //接收外部传来的 执行点击cell item的回调
    private var didSelectItemBlock:(emoji:Emoji)->()
    
    //点击工具栏按钮切换到对应的cell组中
    @objc private func toolBarBtnClick(sender:UIBarButtonItem){
        emojiIconView.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection: sender.tag), atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
    }
    
    
    init(didSelectItem:(emoji:Emoji)->()) {
        self.didSelectItemBlock = didSelectItem
        var rect = UIScreen.mainScreen().bounds
        rect.size.height = 226
        super.init(frame: rect)
        setUI()
        
        //如果没有最近没有表情，设置显示默认表情组
        if emojiPackages[0].emoticons.count == 1 {
        }else{
//            主队列在主线程有任务执行时，不会调度队列中到任务,当执行完一轮runloop后，就会执行该方法
            
            //这里是会造成循环引用的。闭包引用self(控制器),
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                self.emojiIconView.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 1), atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
            })
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit{
        print("88")
    }
    
    //懒加载控件
    private var toolbar:UIToolbar = UIToolbar()
    private var emojiIconView:UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: EmojiFlowLayout())
    
    //定义私有类
    private class EmojiFlowLayout:UICollectionViewFlowLayout{

        
        //在第一布局的时候会调用，或是需要重新计算布局时会调用
        private override func prepareLayout() {
            //一定要调用父类的prepareLayout()
            super.prepareLayout()
            
            //3排7列
            let col:CGFloat = 7
            let row:CGFloat = 3
            
            let cellWidth = UIScreen.mainScreen().bounds.width/col
            
            //计算上下的间距，让整个cell居于collectionView中间
            let topBottomMargin = ((collectionView?.bounds.height)! - row * cellWidth) * 0.4999
            itemSize = CGSizeMake(cellWidth, cellWidth)

            //设置cells内边距
            sectionInset = UIEdgeInsetsMake(topBottomMargin, 0, topBottomMargin, 0)
            
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            scrollDirection = .Horizontal
            collectionView?.pagingEnabled = true
            collectionView?.bounces = false
            collectionView?.showsHorizontalScrollIndicator = false
        }
    }
}


// MARK: - 界面设置
extension EmojiView{
    func setUI(){
        
        addSubview(emojiIconView)
        addSubview(toolbar)
        
        //自动布局
        
        toolbar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(self.snp_bottom)
            make.left.equalTo(self.snp_left)
            make.right.equalTo(self.snp_right)
            make.height.equalTo(44)
        }
        
        
        emojiIconView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_top)
            make.bottom.equalTo(toolbar.snp_top)
            make.left.equalTo(self.snp_left)
            make.right.equalTo(self.snp_right)
        }
        
        prepareToolbar()
        prepareEmojiIconView()
    }
    
    
/// 工具栏的基本准备
    func prepareToolbar(){
        var toolsBtn = [UIBarButtonItem]()
        //根据数组生成一串：按钮+弹簧 ，最后把多余的一个弹簧remove
        
        //tag放置于每个item(区分item)
        var tagIndex = 0
        for package in emojiPackages{
            //因为触发事件需要有事件源参数，所以action名后多打一个冒号等于参数
            let btn = UIBarButtonItem(title: package.group_name_cn, style: UIBarButtonItemStyle.Plain, target: self, action: "toolBarBtnClick:")
            btn.tag = tagIndex++
            toolsBtn.append(btn)
            toolsBtn.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        toolsBtn.removeLast()
        
        toolbar.items = toolsBtn
    }
    
/// 表情图片collectionView的设置
    func prepareEmojiIconView(){
        //注册cell
        emojiIconView.registerClass(EmojiIconViewCell.self, forCellWithReuseIdentifier: EmojiViewCellId)
        emojiIconView.backgroundColor = UIColor.whiteColor()
        //绑定数据源
        emojiIconView.dataSource = self
        emojiIconView.delegate = self
    }
    
}

// MARK: - UICollectionViewDataSource 数据源;UICollectionViewDelegate 代理
extension EmojiView:UICollectionViewDataSource,UICollectionViewDelegate{
    
    //返回多少组
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        print("一共有\(emojiPackages.count)组表情")
        return emojiPackages.count
    }
    
    //每个组有n个emoji表情
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return emojiPackages[section].emoticons.count
    }
    
    //当设置collectionView约束错误时，是无法进入该方法的
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(EmojiViewCellId, forIndexPath: indexPath) as! EmojiIconViewCell
        cell.backgroundColor = UIColor.whiteColor()
        cell.emoji = emojiPackages[indexPath.section].emoticons[indexPath.item]
        return cell
    }
    
    
    //当选中某个cell执行外部传来的闭包，把选中的cell的值以闭包参数传递
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let emojiModel = emojiPackages[indexPath.section].emoticons[indexPath.item]
        
        //传递给外部接受者，所点击的cell的text
        didSelectItemBlock(emoji: emojiModel)
    }
}


/// 每个cell上都放置一个btn，然后btn上显示对应的emoji文字，为了让cell好点击，使用4个点的内边距
private class EmojiIconViewCell:UICollectionViewCell {
    
    //接收emoji模型
    var emoji:Emoji?{
    
        didSet{
            emojiIconBtn.setImage(UIImage(contentsOfFile: emoji!.imagePath), forState: UIControlState.Normal)

            /*
            if emoji?.code != nil{
                emojiIconBtn.setTitle(emoji?.emojiUnicode, forState: UIControlState.Normal)
            }
            */
            
            //以上为错误写法，会照成cell重用；以前用了title的，下次又没有清除，就会显示为一个按钮显示两种类型
            emojiIconBtn.setTitle(emoji?.emojiUnicode, forState: UIControlState.Normal)
            
            //要让emoji显示原始大小，需要设置字体大小为图片大小
            emojiIconBtn.titleLabel?.font = UIFont.systemFontOfSize(32)
            
            //添加每页的删除按钮
            if emoji!.isDeleteBtn == true {
                emojiIconBtn.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
            }
            
            
        }
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //懒加载控件
    lazy var emojiIconBtn:UIButton = UIButton()
    
    //界面设置
    func setUI(){
        contentView.addSubview(emojiIconBtn)
        
        //因为iOS中事件不会穿透，把最上面的btn的交互取消掉就，可以触发cell的点击代理了
        emojiIconBtn.userInteractionEnabled = false
        emojiIconBtn.backgroundColor = UIColor.whiteColor()
        
        //设置btn边缘距离cell的contentView有4个点的距离
        emojiIconBtn.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges).inset(EdgeInsetsMake(4, left: 4, bottom: 4, right: 4))
        }
    }
}












